package com.eco.fanliapp.controller.exapi;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.eco.fanliapp.annotation.SysLogAnnotation;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.QiniuUploadUtils;
import com.eco.fanliapp.utils.StringUtils;
import com.eco.fanliapp.vo.AppGoodsFailure;
import com.eco.fanliapp.vo.CoolqData;
import lombok.Synchronized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 商品（appGoods）controller
 */
@RestController
@RequestMapping("/web/appGoods")
public class AppGoodsController {

    private static final Logger log = LoggerFactory.getLogger(AppGoodsController.class);

    @Autowired
    private IAppGoodsService iAppGoodsService;
    @Autowired
    private IAppGoodsClassifyService appGoodsClassifyService;

    @Autowired
    ISubAccountService subUserService;

    @Autowired
    private ITaoBaoService taoBaoService;

    @Autowired
    private IAppGoodsCoolqService appGoodsCoolqService;

    @Autowired
    private ISyLabelTypeService iSyLabelTypeService;
    @Autowired
    private ISyLabelGoodsService iSyLabelGoodsService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ISyTimePeriodGoodsService iSyTimePeriodGoodsService;

    @Autowired
    private ISyUserClassifyPermissionsService syUserClassifyPermissionsService;

    @Autowired
    RedisTemplate redisTemplate;

    // key过期时间（秒）
    private final Long EXPIRETIME = 60L;

    // 获取首页类目
    @GetMapping("/getClassify")
    @ResponseBody
    public ServerResponse<List<AppGoodsClassify>> getClassify() {
        return taoBaoService.getClassify();
    }

//    @SysLogAnnotation(value = "商品添加", userType = 2)
    @RequestMapping(value = "add")
    public ServerResponse addAppGoods(@RequestBody AppGoods appGoods, Boolean isQqadd) {
        Integer userId = 0;

        if (isQqadd != null && isQqadd) {
            userId = -1;
        } else {
//            if (getAuthentication().getRoleId() != 0) {
//                userId = getAuthentication().getUserId();
//            }
        }

        return iAppGoodsService.addAppGoods(appGoods, userId);
    }

//    @SysLogAnnotation(value = "从QQ群添加商品", userType = 0)
    @RequestMapping(value = "addAppGoodsFromQq")
//    @Transactional
    @Synchronized
    public ServerResponse addAppGoodsFromQq(HttpServletRequest httpServletRequest) {

        Map<String, String[]> httpServletRequestParameterMap = httpServletRequest.getParameterMap();
        String reg = "\\-.+?-";
        log.info("从QQ群添加商品 request=" + JSON.toJSONString(httpServletRequestParameterMap));
        for (String key : httpServletRequestParameterMap.keySet()) {

            QqProduct qqProduct2 = JSON.parseObject(key, QqProduct.class);
            if (qqProduct2 != null && qqProduct2.getType() != null && qqProduct2.getType() == 2
                    && qqProduct2.getGroup() != null
            ) {//如果是qq群消息
                String basePath = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName() + ":" + "8099";
                String productId = null;
                String productTitle = null;
                String productTitle2 = null;
                String facat = null;
//                QueryWrapper<AppGoodsCoolq> queryWrapper = new QueryWrapper<>();
//                queryWrapper.eq("group_id", qqProduct2.getGroup());
//                queryWrapper.eq("sub_type", "2");
//                queryWrapper.eq("enable", "1");
//                Integer count = appGoodsCoolqService.count(queryWrapper);
//                if (count < 1) {
//                    log.info("从QQ群添加商品 失败 该群组不支持=group_id" + qqProduct2.getGroup());
//                    return ServerResponse.createByErrorMessage("从QQ群添加商品 失败 群组不支持");
//                }
                AppGoods appGoods = new AppGoods();
                SyLabelGoods syLabelGoods = new SyLabelGoods();
                String originalMsg = StringUtils.isNull(qqProduct2.getOriginalMsg()) ? qqProduct2.getMsg() : qqProduct2.getOriginalMsg();
                List<SyLabelType> labelType = null;
                if (originalMsg != null) {
//                    String productImage = (qqProduct2.getImageInfo() == null || qqProduct2.getImageInfo().size() <= 0 || qqProduct2.getImageInfo().get(0) == null) ? null : qqProduct2.getImageInfo().get(0).getUrl();
                    String productImage = "";
                    String productImageName = null;
                    String productTkl = "";
                    String label = "";
                    String hour="";
                    String date="";
                    String[] originalMsgs = originalMsg.split("\r\n");
                    for (String originalMsg_ : originalMsgs) {
                        if (StringUtils.isNull(originalMsg_)) {
                            continue;
                        }
                        if (originalMsg_.contains("【商品id】")) {
                            productId = originalMsg_.replace("【商品id】", "").trim();
                        } else if (originalMsg_.contains("item.htm") && originalMsg_.contains("?id=")) {
                            productId = originalMsg_.substring(originalMsg_.indexOf("?id=") + 4).trim();
                        } else if (originalMsg_.contains("【标题】")
                            //|| (!originalMsg_.contains("【") && !originalMsg_.contains("】") && !originalMsg_.contains("http"))
                        ) {
                            productTitle = originalMsg_.replace("【标题】", "").trim();
                        } else if (originalMsg_.contains("【商品淘口令】")) {
                            productTkl = originalMsg_.replace("【商品淘口令】", "").trim();
                            //} else if (!originalMsg_.contains("【") && !originalMsg_.contains("】") && !originalMsg_.contains("http")&& !originalMsg_.contains("image") && StringUtils.isNull(productTitle2) ) {
//                            productTitle2 = originalMsg_;
                        } else if (originalMsg_.contains("【标签】")) {
                            label = originalMsg_.replace("【标签】", "").trim();
                            syLabelGoods.setDeleted(0);
                        } else if (originalMsg_.contains("【取消标签】")) {
                            label = originalMsg_.replace("【取消标签】", "").trim();
                            syLabelGoods.setDeleted(1);
                        } else if (originalMsg_.contains("【秒杀日期】")) {
                            date = originalMsg_.replace("【秒杀日期】", "").trim();
                        }
                        else if (originalMsg_.contains("【秒杀时间】")) {
                            hour=originalMsg_.replace("【秒杀时间】", "").trim();
                        } else if (originalMsg_.matches(reg)) {
                            if (originalMsg_.contains("取消推荐")) {
                                appGoods.setRecommend(0);
                                continue;
                            } else if (originalMsg_.contains("推荐")) {
                                appGoods.setRecommend(1);
                                continue;
                            }
                            try {
                                String facatName = originalMsg_.replaceAll("-", "").trim();
                                if (!StringUtils.isNotNull(facatName)) {
                                    return ServerResponse.createByErrorMessage("商品添加失败，获取不到商品信息类别");
                                }
                                QueryWrapper<AppGoodsClassify> queryWrapper = new QueryWrapper<>();
                                queryWrapper.eq("cname", facatName);
                                List<AppGoodsClassify> appGoodsClassifies = appGoodsClassifyService.list(queryWrapper);
                                if (appGoodsClassifies.size() == 0) {
                                    return ServerResponse.createByErrorMessage("商品添加失败，商品信息类别不正确");
                                } else {
                                    facat = appGoodsClassifies.get(0).getCid() + "";
                                }
                            } catch (Exception e) {
                            }
                        }
                    }
                    //保存秒杀数据
                    if (StringUtils.isNotNull(date)&&StringUtils.isNotNull(hour)){
                        String time= hour.substring(0,hour.indexOf(":"));
                        hour = Integer.valueOf(time) < 10 ? ("0" + hour) : (hour + "");
                        ServerResponse serverResponse=iSyTimePeriodGoodsService.thirdSave(date+" "+hour+":00",hour,productId);
                        log.info("从QQ群添加秒杀商品"+serverResponse.getMsg());
                    }
                    if (StringUtils.isNotNull(productId) || StringUtils.isNotNull(productTkl)) {
                        appGoods.setItemid(productId);
                        appGoods.setItemtitle(productTitle);
//                        appGoods.setItempic(productImage);
                        appGoods.setMsg(productTkl);
                        appGoods.setFqcat(facat);

                        if (StringUtils.isNotNull(productImage)) {
                            productImage = (qqProduct2.getImageInfo() == null || qqProduct2.getImageInfo().size() <= 0 || qqProduct2.getImageInfo().get(0) == null) ? "" : qqProduct2.getImageInfo().get(0).getUrl();
                            productImageName = (qqProduct2.getImageInfo() == null || qqProduct2.getImageInfo().size() <= 0 || qqProduct2.getImageInfo().get(0) == null) ? "" : qqProduct2.getImageInfo().get(0).getFileName();
                            String url = QiniuUploadUtils.uploadFetchImage(productImage, productImageName);
                            appGoods.setItempic(url);
                            log.info("从QQ群添加商品 图片地址=" + url);
                        }

                        if (StringUtils.isNotNull(label)) {
                            labelType = iSyLabelTypeService.findLabelType(label);
                        }
                    }
                }
                if (appGoods != null && StringUtils.isNotNull(appGoods.getItemid())) {
                    ServerResponse serverResponse = iAppGoodsService.addAppGoods(appGoods, -1);

                    if (labelType != null&&labelType.size()>0 && serverResponse.isSuccess()) {
                        SyLabelType syLabelType = labelType.get(0);
                        syLabelGoods.setLabelTypeId(syLabelType.getTableId().toString());
                        syLabelGoods.setLabelCode(syLabelType.getLabelCode());
                        syLabelGoods.setCreateTime(new Date());
                        syLabelGoods.setUpdateTime(new Date());
                        syLabelGoods.setItemId(appGoods.getItemid());

                        int i = iSyLabelGoodsService.addSyLabelGoods(syLabelGoods);
                        if (i > 0) {
                            log.info("商品标签添加成功 syLabelGoods=" + JSON.toJSONString(syLabelGoods));
                        }
                    }
                    CoolqData data = new CoolqData();
                    data.setGroup(qqProduct2.getGroup());
                    data.setMsg(StringUtils.isNull(productTitle) ? productTitle2 : productTitle + " " + serverResponse.getMsg());
                    data.setFun("sendGroupMsg");
                    iAppGoodsService.sendSocketData(basePath, data.toJson());

                    log.info("从QQ群添加商品结果 appGoods=" + JSON.toJSONString(appGoods) + "--serverResponse=" + JSON.toJSONString(serverResponse));
                    return serverResponse;
                }

            }
        }


        return ServerResponse.createByErrorMessage("商品添加失败，商品信息不完整");
    }

    public static void main(String args[]) {
//        CoolqData data = new CoolqData();
//        data.setGroup(135932737L);
//        data.setMsg("ceshi 成功");
//        data.setFun("sendGroupMsg");
        String aa = "-11230a";
        String reg = "\\-.+?-";

//        a.sendSocketData("http://localhost:8099", data.toJson());
    }


//    @SysLogAnnotation(value = "商品拉取", userType = 0)
    @RequestMapping(value = "out")
    public ServerResponse out(HttpServletRequest request, String company, Integer minId, Integer pageSize, Integer cid, String itemid) {
        log.info("商品拉取  请求参数：" + JSON.toJSONString(request.getParameterMap()));
        // 获取请求IP
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "null".equals(ip)) {
            ip = "" + request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "null".equals(ip)) {
            ip = "" + request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip) || "null".equals(ip)) {
            ip = "" + request.getRemoteAddr();
        }
        // 前缀+ip构成key
        String key = company + ip;
        //检查key是否存在，返回boolean值
        boolean flag = stringRedisTemplate.hasKey(key);
        String sumVal = "";
        int sum = 0;
        if (flag) {
            // 调用次数+1
            stringRedisTemplate.boundValueOps(key).increment(1);
            // 设置过期时间
            stringRedisTemplate.expire(key, EXPIRETIME, TimeUnit.SECONDS);
            sumVal = stringRedisTemplate.opsForValue().get(key);
            sum = Integer.valueOf(sumVal);
        } else {
            // 第一次调用，所以value（调用次数）设置为1
            stringRedisTemplate.opsForValue().set(key, "1", EXPIRETIME, TimeUnit.SECONDS);
        }
        if (sum <= 60) {
            //查询商品

            minId = minId == null ? 0 : minId;
            pageSize = pageSize == null ? 20 : pageSize;
            pageSize = pageSize < 20 ? 20 : pageSize;
            pageSize = pageSize > 5000 ? 5000 : pageSize;
            cid = cid == null ? -1 : cid;

            if (StringUtils.isNotNull(itemid)) {
                AppGoods good = iAppGoodsService.findAppGoodsByItemId(itemid);
                if (good != null) {
                    return ServerResponse.createBySuccess("数据获取成功", good);
                } else {
                    return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
                }
            }

            List<AppGoods> goods = iAppGoodsService.selectGoodsList(minId, pageSize, cid);
            if (goods != null && goods.size() > 0) {
                Map map = new HashMap();
                map.put("minId", goods.get(goods.size() - 1).getTableId());
                map.put("goods", goods);
                log.info("商品拉取返回数据 data=" + JSON.toJSONString(map));
                return ServerResponse.createBySuccess("数据获取成功", map);
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
            }
        } else {
            String num = stringRedisTemplate.opsForValue().get(key);
            return ServerResponse.createBySuccess("第" + sum + "次请求 ,一分钟内不能再次请求！");
        }
    }

    /**
     * 对外接口-获取失效商品
     *
     * @param request
     * @param company
     * @param start
     * @param end
     * @return
     */
//    @SysLogAnnotation(value = "失效商品", userType = 0)
    @RequestMapping(value = "getDownItems")
    public ServerResponse getDownItems(HttpServletRequest request, @RequestParam(defaultValue = "shengya") String company, @RequestParam(defaultValue = "0") Integer start, @RequestParam(defaultValue = "1") Integer end) {
        String day = DateFormatUtils.getNowDateDay(new Date());
        log.info("失效商品***********" + day);
        List<AppGoodsFailure> failureLists = new ArrayList<>();
        while (true) {
            if (start > end) {
                break;
            }
            String starTime = start < 10 ? ("0" + start) : (start + "");
            //日期加时间timeGoodsList
            String time = day + "-" + starTime;
            try {
                List<AppGoodsFailure> failureList = (List<AppGoodsFailure>) redisTemplate.opsForList().range("failureAppGoods" + time, 0, -1);
                if (failureList != null) {
                    failureLists.addAll(failureList);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            start++;
        }
        if (failureLists.size() != 0) {

            List<AppGoodsFailure> appGoodsFailures = new ArrayList<>();
            Set<String> failureSet = new HashSet();
            for (AppGoodsFailure app : failureLists) {
                if (failureSet.contains(app.getItemid())) {
                    continue;
                }
                failureSet.add(app.getItemid());
                appGoodsFailures.add(app);

            }

            return ServerResponse.createBySuccess("获取失效商品成功", appGoodsFailures);
        }
        return ServerResponse.createByErrorMessage("没有获取到失效商品");
    }

    /**
     * 对外接口-获取更新商品
     *
     * @param request
     * @param company
     * @param pageSize
     * @param cid
     * @param minId
     * @return
     */
//    @SysLogAnnotation(value = "提供商品更新", userType = 0)
    @RequestMapping(value = "updateItem")
    public ServerResponse updateItem(HttpServletRequest request, String company, @RequestParam(defaultValue = "100") Integer pageSize, @RequestParam(defaultValue = "-1") Integer cid, @RequestParam(defaultValue = "0") String minId) {
        minId = minId == null ? "0" : minId;
        pageSize = pageSize == null ? 20 : pageSize;
        pageSize = pageSize < 20 ? 20 : pageSize;
        pageSize = pageSize > 5000 ? 5000 : pageSize;
        cid = cid == null ? -1 : cid;
        List<AppGoods> goods = iAppGoodsService.getUpdateItem(minId, pageSize, cid);
        Map map = new HashMap();
        if (goods != null && goods.size() > 0) {
            minId = goods.get(goods.size() - 1).getFanliUpdateTime();
            map.put("minId", minId);
            map.put("goods", goods);
            return ServerResponse.createBySuccess("商品更新数据获取成功", map);
        }
        return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
    }

    /**
     * 对外接口-获取今日更新商品
     *
     * @param request
     * @param company
     * @param pageSize
     * @param cid
     * @param minId
     * @return
     */
//    @SysLogAnnotation(value = "提供今日商品", userType = 0)
    @RequestMapping(value = "timingItems")
    public ServerResponse timingItems(HttpServletRequest request, String company,
                                      @RequestParam(defaultValue = "100") Integer pageSize,
                                      @RequestParam(defaultValue = "-1") Integer cid,
                                      @RequestParam(defaultValue = "0") Integer start,
                                      @RequestParam(defaultValue = "1") Integer end,
                                      @RequestParam(defaultValue = "0") String minId) {

        QueryWrapper<AppGoods> appGoodsQueryWrapper = new QueryWrapper<>();

        if (cid == 0) {
            appGoodsQueryWrapper.eq("recommend", 1);
        } else if (cid > 0) {
            appGoodsQueryWrapper.eq("fqcat", cid);
        } else {

        }

        minId = minId == null ? "0" : minId;
        pageSize = pageSize == null ? 20 : pageSize;
        pageSize = pageSize < 20 ? 20 : pageSize;
        pageSize = pageSize > 5000 ? 5000 : pageSize;

        String today = DateFormatUtils.getNowDateDay(new Date());

        String startTime = "";
        String endTime = "";
        if (start < 10) {
            startTime = today + " 0" + start + ":00:00";
        } else {
            startTime = today + " " + start + ":00:00";
        }
        if (end < 10) {
            endTime = today + " 0" + end + ":59:59";
        } else {
            endTime = today + " " + end + ":59:59";
        }
        appGoodsQueryWrapper.ge("create_time", DateFormatUtils.string2dateTime(startTime));
        appGoodsQueryWrapper.le("create_time", DateFormatUtils.string2dateTime(endTime));

        appGoodsQueryWrapper.ge("table_id", minId);

        appGoodsQueryWrapper.orderByAsc("table_id");
        appGoodsQueryWrapper.last("limit " + pageSize);

        List<AppGoods> goods = iAppGoodsService.list(appGoodsQueryWrapper);

        if (goods != null && goods.size() > 0) {
            Map map = new HashMap();
            map.put("minId", goods.get(goods.size() - 1).getTableId());
            map.put("goods", goods);
            return ServerResponse.createBySuccess("今日更新商品数据获取成功", map);
        }
        return ServerResponse.createBySuccessCodeMessage(201, "没有更多商品");
    }

    /**
     * 对外接口-获取商品詳情
     *
     * @param pageSize
     * @param userId
     * @param minId
     * @return
     */
//    @SysLogAnnotation(value = "提供商品查询", userType = 0)
    @RequestMapping(value = "findItem")
    public ServerResponse findItem(HttpServletRequest request, String company, Long userId,
                                   String userName, @RequestParam(defaultValue = "100") Integer pageSize,
                                   String password, @RequestParam(defaultValue = "0") String minId) {

        //判断用户
        List<SyUserClassifyPermissions> syUserClassifyPermissions = querySyUserClassifyPermissions(userId, userName, password);
        if (syUserClassifyPermissions != null && syUserClassifyPermissions.size() > 0) {

            //分页查询，按照更新时间倒叙排，（一个用户只能查询一种分类的）
            List<AppGoods> goods = iAppGoodsService.findItem(userId, pageSize, minId, syUserClassifyPermissions.get(0).getClassifyId());
            if (goods != null && goods.size() > 0) {
                Map map = new HashMap();
                map.put("minId", DateFormatUtils.dateToString(goods.get(goods.size() - 1).getUpdateTime()));
                map.put("goods", goods);
                return ServerResponse.createBySuccess("获取商品成功", map);
            }
            return ServerResponse.createBySuccessCodeMessage(201, "没有所属商品");
        }
        return ServerResponse.createBySuccessMessage("用户验证失败");
    }

    /**
     * 对外接口-商品刪除
     *
     * @param userId
     * @param itemid
     * @return
     */
//    @SysLogAnnotation(value = "提供商品删除", userType = 0)
    @RequestMapping(value = "deleItem")
    public ServerResponse deleItem(HttpServletRequest request, Long userId, String userName, String password, String itemid) {

        //判断用户
        List<SyUserClassifyPermissions> syUserClassifyPermissions = querySyUserClassifyPermissions(userId, userName, password);
        if (syUserClassifyPermissions != null && syUserClassifyPermissions.size() > 0) {
            //删除数据库内商品（一个用户只能删除自己所属分类的商品）
            List<AppGoods> goods = iAppGoodsService.selectItem(userId, itemid, syUserClassifyPermissions.get(0).getClassifyId());
            if (goods != null && goods.size() > 0) {
                int i = iAppGoodsService.deleteAppGoodsById(goods.get(0).getTableId());
                if (i > 0) {
                    return ServerResponse.createBySuccess("删除商品成功");
                } else {
                    return ServerResponse.createByErrorMessage("删除商品失败");
                }
            } else {
                return ServerResponse.createBySuccessCodeMessage(201, "没有所属商品");
            }
        }
        return ServerResponse.createBySuccessMessage("用户验证失败");
    }

    public List<SyUserClassifyPermissions> querySyUserClassifyPermissions(Long userId, String userName, String password) {
        QueryWrapper<SyUserClassifyPermissions> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("user_name", userName);
        queryWrapper.eq("password", password);
        queryWrapper.eq("enable", 1);
        queryWrapper.eq("deleted", 0);
        List<SyUserClassifyPermissions> syUserClassifyPermissions = syUserClassifyPermissionsService.list(queryWrapper);
        return syUserClassifyPermissions;
    }

}
